var pomelo = require('pomelo');
var async = require('async');
var wt = require('async').waterfall;
var each = require('async').each;

var mysql = require('../dao/userDao');  // mysqlClient
var utils = require('../util/utils');


var log = console.log;

module.exports = function (app, opts) {
    return new loadMysqlConfig(app, opts);
};

var DEFAULT_INTERVAL = 3000;

var loadMysqlConfig = function (app, opts) {
    this.app = app;
    // this.interval = opts.interval || DEFAULT_INTERVAL;
    this.timerId = null;
};

loadMysqlConfig.name = '__loadMysqlConfig__';

loadMysqlConfig.prototype.start = function (cb) {
    console.log('loadMysqlConfig Start');
    var client = pomelo.app.get('redisUser');  // redisClient
    var self = this;
    var configs = {};
    var gameId, config;
    // var keys = [];
    wt([
        function (wcb) {
            // 读取mysql配置
            mysql.query('select id, configs from game_info', [], function (err, rows) {
                if (err) {
                    wcb(err);
                    throw err;
                }
                else {
                    console.log('读取mysql配置成功');
                    // log(rows);
                    var len = rows.length;
                    for (var i = 0; i < len; i++) {
                        gameId = rows[i].id;
                        config = rows[i].configs;
                        if (!config) {
                            continue;
                        }

                        config = JSON.parse(config);

                        if (!config.id) {
                            config.id = gameId;
                        }  // 如果没有配置config.id
                        config = JSON.stringify(config);
                        configs[gameId] = config;
                        // keys.push(gameId);
                    }
                    console.log(configs);
                    // key = rows[0].id + 'gameConfig';
                    wcb();
                }
            });
        },
        function (wcb) {
            // 如果有多个游戏，可能需要写入在多个地方
            // 写入redis
            async.eachLimit(configs, 1,
                function (config, ecb) {
                    var key = 'gameConfig' + JSON.parse(config).id;
                    client.set(key, config, function (err, rel) {
                        if (err) {
                            console.log(err);
                            ecb(err);
                        }
                        else {
                            // console.log('设置redis配置成功');
                            // log(key);
                            // log(JSON.parse(config));
                            ecb();
                        }
                    });
                },
                function (err, rel) {
                    if (err) {
                        console.log(err);
                        wcb(err);
                    }
                    else {
                        wcb();
                    }
                });
        },
        function (wcb) {
            // 读取redis
            async.eachLimit(configs, 1,
                function (config, ecb) {
                    var key = 'gameConfig' + JSON.parse(config).id;
                    client.get(key, function (err, rel) {
                        if (err) {
                            console.log(err);
                            ecb(err);
                        }
                        else {
                            // console.log('读取redis配置成功');
                            // log(key + ': ');
                            // log(JSON.parse(config));
                            ecb();
                        }
                    });
                },
                function (err, rel) {
                    if (err) {
                        console.log(err);
                        wcb(err);
                    }
                    else {
                        wcb();
                    }
                });
        }
    ],
        function (err, rel) {
            if (!err) {
                process.nextTick(cb);
            }
        });
    // mysql.query('select * from game_info where id = 1', [], function (err, rows) {
    //     if (err) throw err;
    //     console.log(rows.length);
    //     console.log(rows[0]);
    //     process.nextTick(cb);
    // });
    //   this.timerId = setInterval(function() {
    //     console.log(self.app.getServerId() + ": loadMysqlConfig!");
    //     }, this.interval);
    //   process.nextTick(cb);
};

loadMysqlConfig.prototype.afterStart = function (cb) {
    console.log('loadMysqlConfig afterStart');
    // clearInterval(this.timerId);
    process.nextTick(cb);
    // log(this.app.get('sessionService'));
};

loadMysqlConfig.prototype.stop = function (force, cb) {
    console.log('loadMysqlConfig stop');
    process.nextTick(cb);
};
